package controllers

import (
	"alerts/models"
	beego "github.com/beego/beego/v2/server/web"
)

type NewControllers struct {
	beego.Controller
}
type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewControllers) Add() {
	name := c.GetString("name")
	times := c.GetString("times")
	types := c.GetString("types")

	if name == "" || times == "" || types == "" {
		c.Data["json"] = Msg{
			Code: 0,
			Msg:  "不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	news := models.Alert{
		Name:  "",
		Times: "",
		Types: "",
	}
	err := models.DB.Create(&news).Error
	if err != nil {
		c.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Msg{
			Code: 200,
			Msg:  "添加成功",
			Data: news,
		}
		c.ServeJSON()
	}

}

func (c *NewControllers) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Alert{}, id).Error
	if err != nil {
		c.Data["json"] = Msg{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Msg{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *NewControllers) List() {
	var news []models.Alert
	err := models.DB.Find(&news).Error
	if err != nil {
		c.Data["json"] = Msg{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Msg{
			Code: 200,
			Msg:  "展示成功",
			Data: news,
		}
		c.ServeJSON()
	}
}
